import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JPanel;


public class ColorPicker extends JPanel implements MouseListener {
	
	private ArrayList<java.awt.Rectangle> colorBlocks;
	private Rectangle showColor;
	private Color selectedColor;
	private HashMap<Rectangle, Color> colorMap;
	private CourierCanvas canvas;
	
	public ColorPicker(CourierCanvas c) {
		this.canvas = c;
		//this.setMinimumSize(new Dimension(300,300));
		this.setPreferredSize(new Dimension(80, 40));
		Rectangle r;
		int width = 12;
		int height = 12;
		colorBlocks = new ArrayList<Rectangle>();
		colorMap = new HashMap<Rectangle, Color>();
		for(int i = 0; i < 3; i++){
			for(int j = 0; j < 3; j++){
				r = new Rectangle(i*width,j*height, width, height);
				switch (i*3 + j){
				case 0:
					colorMap.put(r, Color.black);
					break;
				case 1:
					colorMap.put(r, Color.white);
					break;
				case 2:
					colorMap.put(r, Color.cyan);
					break;
				case 3:
					colorMap.put(r, Color.red);
					break;
				case 4: 
					colorMap.put(r, Color.orange);
					break;
				case 5:
					colorMap.put(r, Color.yellow);
					break;
				case 6:
					colorMap.put(r, Color.magenta);
					break;
				case 7:
					colorMap.put(r, Color.blue);
					break;
				case 8:
					colorMap.put(r, Color.green);
				}
				colorBlocks.add(r);
			}
		}
		
		showColor = new Rectangle(12 + 3*width, 0, 30, 30 );
		selectedColor = Color.black;
		this.addMouseListener(this);
	}
	
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D)g;
		for ( Rectangle r : colorBlocks){
			g2.setColor(Color.BLACK);
			g2.drawRect(r.x, r.y, r.width, r.height);
			g2.setColor(colorMap.get(r));
			g2.fillRect(r.x + 1, r.y+1, r.width - 1, r.height - 1);
		}
		g2.setColor(Color.black);
		g2.drawRect(showColor.x, showColor.y, showColor.width, showColor.height);
		g2.setColor(selectedColor);
		g2.fillRect(showColor.x + 1, showColor.y + 1, showColor.width - 1, showColor.height - 1);
	}

	@Override
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		for(Rectangle r : colorBlocks){
			if(r.contains(e.getPoint())){
				selectedColor = colorMap.get(r);
				repaint();
				canvas.setColor(selectedColor);
			}
		}
		
	}

}
